import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import type { ColorPickerProps, GetProp } from 'antd';
import { ColorPicker, Flex, List, message, Tabs } from 'antd';
import Search from 'antd/es/input/Search';
import usePictureTagCategory from '@/hooks/usePictureTagCategory';
import CheckableTag from 'antd/es/tag/CheckableTag';
import {
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/services/backend/pictureController';
import PictureCard from '@/components/PictureCard';
import { useNavigate } from '@umijs/max';
import QrCodeModal from '@/components/QrCodeModal';

type Color = Extract<GetProp<ColorPickerProps, 'value'>, string | { cleared: any }>;
type Format = GetProp<ColorPickerProps, 'format'>;

const IndexPage: React.FC = () => {
  const DEFAULT_PAGE_PARAMS: PageRequest = {
    current: 1,
    pageSize: 12,
    sortField: 'createTime',
    sortOrder: 'descend',
  };
  const navigate = useNavigate();
  const [loading, setLoading] = React.useState<boolean>(true);
  const [dataList, setDataList] = React.useState<API.PictureVO[]>([]);
  const [total, setTotal] = React.useState<number>(0);
  const [searchParam, setSearchParam] = React.useState<API.PictureQueryRequest>({
    ...DEFAULT_PAGE_PARAMS,
  });
  const [qrCodeModalVisible, setQrCodeModalVisible] = useState<boolean>(false);
  const [qrCodeValue, setQrCodeValue] = useState<string>('');
  const { tagList, categoryList } = usePictureTagCategory();
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>();
  const [colorHex, setColorHex] = useState<Color>('#1677ff');
  const [formatHex, setFormatHex] = useState<Format | undefined>('hex');

  const hexString = React.useMemo<string>(
    () => (typeof colorHex === 'string' ? colorHex : colorHex?.toHexString()),
    [colorHex],
  );
  const handleChange = (tag: string, checked: boolean) => {
    const nextSelectedTags = checked
      ? [...selectedTags, tag]
      : selectedTags.filter((t) => t !== tag);
    setSelectedTags(nextSelectedTags);
    setSearchParam({
      ...searchParam,
      tags: nextSelectedTags,
    });
  };
  const doSearch = async () => {
    setLoading(true);
    try {
      const res = await listPictureVoByPageUsingPost(searchParam);
      setDataList(res.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } catch (e: any) {
      message.error('获取数据失败：' + e.message);
    }
    setLoading(false);
  };
  const doSearchByColor = async () => {
    setLoading(true);
    try {
      const res = await searchPictureByColorUsingPost({
        picColor: hexString,
      });
      setDataList(res.data ?? []);
      setTotal(res.data?.length ?? 0);
    } catch (e: any) {
      message.error('获取数据失败：' + e.message);
    }
    setLoading(false);
  };
  useEffect(() => {
    doSearch();
  }, [searchParam]);
  return (
    <PageContainer title={<></>}>
      <Flex justify={'center'}>
        <Search
          style={{
            width: '40vw',
            minWidth: '250',
          }}
          placeholder="从海量图片中搜索"
          allowClear
          enterButton="搜索"
          size="middle"
          onSearch={(value: string) => {
            setSearchParam({
              ...DEFAULT_PAGE_PARAMS,
              tags: selectedTags,
              category: selectedCategory,
              searchText: value,
            });
          }}
        />
      </Flex>

      <Tabs
        style={{ marginTop: 24 }}
        defaultActiveKey="0"
        onChange={(activeKey) => {
          let selectedLabel = undefined;
          if (activeKey === '0') {
            setSelectedCategory(undefined);
          } else {
            selectedLabel = categoryList[parseInt(activeKey)];
          }
          setSearchParam({
            ...searchParam,
            category: selectedLabel,
          });
        }}
        items={categoryList.map((item, index) => {
          return {
            label: item, // Tab 的标签显示内容
            key: index + '', // 使用字符串作为 key
            children: '',
          };
        })}
      />

      {tagList.map((tag) => (
        <CheckableTag
          key={tag}
          checked={selectedTags.indexOf(tag) > -1}
          onChange={(checked) => handleChange(tag, checked)}
        >
          {tag}
        </CheckableTag>
      ))}
      <br />
      <ColorPicker
        defaultValue="#1677ff"
        size="small"
        showText
        format={formatHex}
        value={colorHex}
        onChange={async (color) => {
          setColorHex(color);
          await doSearchByColor();
        }}
        onFormatChange={setFormatHex}
        style={{ marginTop: 16 }}
      />
      <List<API.PictureVO>
        style={{ marginTop: 16 }}
        rowKey="id"
        grid={{
          gutter: 16,
          xs: 1,
          sm: 2,
          md: 3,
          lg: 3,
          xl: 4,
          xxl: 4,
        }}
        pagination={{
          current: searchParam.current,
          pageSize: searchParam.pageSize,
          total: total,
          onChange: (current, pageSize) => {
            setSearchParam({
              ...searchParam,
              current: current,
              pageSize: pageSize,
            });
          },
        }}
        loading={loading}
        dataSource={dataList}
        renderItem={(data) => (
          <List.Item key={data.id} style={{}}>
            <PictureCard
              canSearch={true}
              canShare={true}
              data={data}
              onSearch={() => {
                navigate(`/picture/search/${data.id}`);
              }}
              onShare={() => {
                const shareLink = `${window.location.protocol}//${window.location.host}/picture/${data.id}`;
                setQrCodeValue(shareLink);
                setQrCodeModalVisible(true);
              }}
            />
          </List.Item>
        )}
      ></List>
      <QrCodeModal
        title={'分享图片'}
        visible={qrCodeModalVisible}
        value={qrCodeValue}
        onCancel={() => {
          setQrCodeModalVisible(false);
        }}
      ></QrCodeModal>
    </PageContainer>
  );
};

export default IndexPage;
